# -*- coding: utf-8 -*-
# @Time    : 2023/12/31  21:33
# @Author  : zhanghao
# @FileName: rule_actuator.py
# @Software: PyCharm
"""
    Description: 根据规则配置和内容重命名文件
"""
import collections
import json
import os
import re

from config.config import Config
from config.logger import Logger
from domain.rule import Rule
from domain.rename import Rename
from core.ocr_result import OcrResult
from helper.file_helper import FileHelper


class RuleActuator:
    logger = Logger.get()

    config: Config
    rules: [Rule]

    def __init__(self, config: Config):
        self.logger.info('初始化规则数量: ' + str(len(config.rule_config.rules)))
        self.config = config
        self.rules = config.rule_config.rules

    # 遍历规则进行匹配
    def processContent(self, content: OcrResult):
        self.logger.info('识别文本，规则数量：' + str(len(self.rules)))

        result_list = []
        for rule in self.rules:
            keyword_list = [rule.keyword]
            for rename in rule.rename:
                if rename.match_type == 'keyword':
                    keyword_list.append(rename.info)

            keyword_match = True
            for word in keyword_list:
                if word not in content.text:
                    keyword_match = False

            # 确定一个规则类型
            if keyword_match:
                execute_result = self.ruleExecute(rule, content)
                result_list.append(execute_result)

        return self.getOneResult(result_list)

    # 执行规则
    def ruleExecute(self, rule: Rule, content: OcrResult):
        self.logger.info('ruleExecute' + rule.keyword + ' rule len' + str(len(rule.rename)))
        execute_result = collections.OrderedDict()

        for rename in rule.rename:
            if rename.match_type == 'regex':
                result = self.regexExecute(rename, content)
                execute_result[rename.name] = result
            elif rename.match_type == 'keyword':
                result = self.keywordExecute(rename, content)
                execute_result[rename.name] = result

        if len(execute_result) > 0:
            execute_result['retFileName'] = rule.ret_file_name
            execute_result['classifyId'] = rule.classify_id
        self.logger.info(execute_result)
        return execute_result

    # 正则执行器
    def regexExecute(self, rename: Rename, content: OcrResult):
        result = ''
        if rename.name == 'caseNo':
            pattern = re.compile(rename.info)
            search_result = re.findall(pattern, content.text)
            if search_result and len(search_result) > 0:
                for case_no in search_result:
                    if len(case_no) > 0:
                        result = case_no[0]
                        if result and len(result) > 0:
                            break
        elif rename.name == 'defendantName':
            pattern = re.compile(rename.info)
            search_result = re.findall(pattern, content.text)
            if search_result and len(search_result) > 0:
                for defendant in search_result:
                    if len(result) == 0:
                        result = defendant[1]
                    else:
                        if defendant[1] not in result and len(defendant[1]) < 4:
                            result = result + '、' + defendant[1]

            if len(result) == 0:
                # 特殊情况匹配被告
                result = self.specialDefendantName(content.text)
        else:
            pattern = re.compile(rename.info)
            search_result = re.findall(pattern, content.text)
            if search_result and len(search_result) > 0:
                result = search_result[0]
        return result

    # 关键字执行器
    def keywordExecute(self, rename: Rename, content: OcrResult):
        keyword = rename.info

        execute_result = []
        # 拆分关键字
        result = keyword.split('#')
        if result and len(result) > 0:
            for word in result:
                if word in content.text:
                    execute_result.append(word)

        return execute_result

    def identifyCaseNo(self, regex_info, content):
        result = ''
        pattern = re.compile(regex_info)
        search_result = re.findall(pattern, content)
        if search_result and len(search_result) > 0:
            for defendant in search_result:
                if len(defendant) > 0:
                    result = defendant[0]
                    if result and len(result) > 0:
                        break

        return result

    def specialDefendantName(self, content):
        case_no_regex = Rule.case_no_regex
        case_no = self.identifyCaseNo(case_no_regex, content)

        result = ''
        if len(case_no) > 0:
            defendant_regex = case_no + '([\\u4e00-\\u9fa5]+)[:：]{1}'
            pattern = re.compile(defendant_regex)
            search_result = re.findall(pattern, content)
            if len(search_result) > 0:
                result = search_result[0]

        if len(result) > 4:
            result = ''

        return result

    # 判断多个识别结果，如果关键字出现在案号中则优先返回
    def getOneResult(self, result_list):
        execute_result = collections.OrderedDict()
        if len(result_list) == 0:
            return execute_result

        if len(result_list) == 1:
            return result_list[0]

        for result_dict in result_list:
            execute_result = result_dict
            case_no = result_dict['caseNo']

            if 'keywords' not in result_dict.keys():
                continue
            keywords = result_dict['keywords']

            pri = True
            for word in keywords:
                if word not in case_no:
                    pri = False

            if pri:
                break

        return execute_result
